package com.dzq.controls
{
	import flash.display.Graphics;
	import flash.events.MouseEvent;
	
	import mx.core.Container;
	import mx.events.FlexEvent;
	
	/**
	 * @author DUZENGQIANG http://www.duzengqiang.com
	 * @date 2008-05-29 
	 * @sample
	 * var vc:VolumeControl = new VolumeControl();
  		addChild(vc);
  		vc.addEventListener(FlexEvent.DATA_CHANGE, function(e:FlexEvent):void{
  			Alert.show(vc.value+'');
  		});
	 * 
	 */
public class VolumeControl extends Container
{
	private var _x:Number;
	private var _width:Number = 100;
	private var _height:Number = 50;
				
	private var _value:int = 0;
	
	/**
	 * minimum value
	 */
	public var min:int = 0;
	
	/**
	 * maximum value
	 */
	public var max:int = 10;
	
	/**
	 * Color Block Width
	 */
	public var blockWidth:Number = 8;
	
	/**
	 * Gap width
	 */
	public var gap:Number = 2;
	
	/**
	 * Color Block's Enabled Color
	 */
	public var enabledColor:uint = 0xfe6600;
	
	/**
	 * Color Block's disabled Color
	 */
	public var disabledColor:uint = 0x969696;
	
	public function set value(value:int):void{
		_value = value;
		_x = value / (max - min) * _width;
		drawChart();
	}
	public function get value():int{
		return int(((_x *(max - min)/_width) as Number).toFixed());
	}
	
	override public function set width(value:Number):void{
		_width = value;
		if(_height != 0)drawChart();
	}
	
	override public function set height(value:Number):void{
		_height = value;
		if(_width != 0)drawChart();
	}
	
	public function VolumeControl()
	{				
		width = 100;
		height = 50;
		addEventListener(MouseEvent.CLICK, onMouseDown);		
	}
	
	private function drawChart():void{
  		var g:Graphics = graphics;
  		g.clear()
  		var j:int = 0;
       	for(var i:int=0; i<=_width; i+= blockWidth + gap){
       		if( i + blockWidth + gap <= _width || i + blockWidth <= _width){
       			if(i  <= _x){
	       			g.beginFill(enabledColor);
	       		}else{
	       			g.beginFill(disabledColor);
	       		}
	       		
	       		var _h:Number =_height /( _width /(blockWidth + gap)) * j + 2;	
	     		g.drawRect(i, _height - _h, blockWidth, _h);
	     		j++;
       		}else{
       			if(i  <= _x){
	       			g.beginFill(enabledColor);
	       		}else{
	       			g.beginFill(disabledColor);
	       		}
	       		
	       		var _h:Number =_height /( _width /(blockWidth + gap)) * j + 2;	
	     		g.drawRect(i, _height - _h, _width - i, _h);
	     		j++;
       		}
       		
     	}
    }
    
    private function onMouseDown(e:MouseEvent):void{
    	_x = e.localX;
    	drawChart();
    	dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE));
    }

}
}